package day08;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Demo04 {
    public static void main(String[] args) {
        /*
         * CGLib动态代理
         */
        Enhancer e = new Enhancer();
        //设置被继承的父类型
        e.setSuperclass(ArrayList.class);
        //设置方法拦截器
        e.setCallback(new CallInterceptor<String>());
        //创建代理对象
        List<String> list = (List<String>) e.create();
        //测试代理对象的功能
        list.add("Tom");
        list.add("Jerry");
        System.out.println(list);
        System.out.println(list.getClass());
    }
}
class CallInterceptor<E> implements MethodInterceptor{
    private List<E> target = new ArrayList<>();
    @Override
    public Object intercept(
            Object proxy, Method method,
            Object[] args, MethodProxy methodProxy)
            throws Throwable {
        System.out.println(method);
        Object value=method.invoke(target,args);
        return value;
    }
}
